package pay.task;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import pay.common.ConstantFYJZH;
import pay.common.HqlFilter;
import pay.context.FYContext;
import pay.enm.WithdrawStatusEnum;
import pay.entity.Parameter;
import pay.entity.Trade;
import pay.portal.web.message.CZTXRecord;
import pay.service.IMessageService;
import pay.service.IParameter;
import pay.service.ITrade;
import pay.utils.ConstantPush;
import pay.utils.MsgTypeConstants;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 检验是否提现退票
 * @author Evan
 * @date 2018/1/8
 */
@Component
public class WithdrawTask {
    private final Logger log = LoggerFactory.getLogger(WithdrawTask.class);

    @Autowired
    private FYContext fyContext;

    @Autowired
    private ITrade tradeService;

    @Autowired
    private IParameter parameterService;

    @Autowired
    private IMessageService messageService;

    /**
     * 系统参数配置（单位秒）提现检测时间
     */
    private final String WITHDRAW_CHECK_TIME = "WITHDRAW_CHECK_TIME";

    @Scheduled(cron = "0 0/2 * * * ?")
    private void run(){

        log.info("WithdrawTask start! time = "+ new Date());
        HqlFilter hql = new HqlFilter();
        hql.addEQFilter("withdrawStatus", WithdrawStatusEnum.AUDITING);
        List<Trade> list = tradeService.findByFilter(hql);
        log.info("WithdrawTask size={}",list.size());
        list.parallelStream().forEach(t -> check(t));
    }

    private void check(Trade trade){
        Parameter parameter = parameterService.getByName(WITHDRAW_CHECK_TIME);

        //系统参数配置（单位秒），如果超过该时间没有发生退票，则认为提现成功
        Integer customTime = 1800;
        if(parameter != null && StringUtils.isNotBlank(parameter.getValue01())){
            customTime = Integer.valueOf(parameter.getValue01());
        }
        long withdrawTime = trade.getCts();
        if(System.currentTimeMillis() - withdrawTime > customTime*1000){
            trade.setWithdrawStatus(WithdrawStatusEnum.SUCCUSS);
            tradeService.update(trade);
            return;
        }

        //查看有没有发生退票
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.plusSeconds(-customTime);
        List<CZTXRecord> fyRecord = fyContext.getResult(ConstantFYJZH.BUSI_TY_TP, trade.getLogin_id(), startTime.format(formatter), endTime.format(formatter));

        fyRecord.stream().forEach(c -> {
            if(c.getMchnt_ssn().equals(trade.getMchnt_txn_ssn())){

                //如果在进行定时任务的时候，刚好发生了富友回调就不再处理
                Trade checkAgain = tradeService.findById(trade.getId());
                if(WithdrawStatusEnum.AUDITING.equals(checkAgain.getWithdrawStatus())){
                    log.info("用户:{}发生退票",trade.getLogin_id());
                    trade.setWithdrawStatus(WithdrawStatusEnum.FAIL);
                    trade.setResp_code("0001");
                    trade.setResp_desc("退票");
                    tradeService.update(trade);
                    String msg = String.format("您申请提现一笔 %s 元的资金提现失败，请重新操作。",trade.getAmt());
                    this.messageService.sendMsg(String.valueOf(trade.getUserId()), msg, "提现失败", ConstantPush.WITHDRAW, MsgTypeConstants.WITHDRAW);
                }
            }
        });
    }
}
